import 'dart:math';
import 'package:common/common.dart';

/// header拦截器
class HeaderInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    options.headers["Accept"] = "application/json";
    var localeCode = await SPUtils.get(CacheConstants.locale);
    if (localeCode is String && localeCode.isEmpty) {
      localeCode = "zh-CN";
    }
    options.headers["Accept-Language"] = localeCode?? "zh-CN";
    options.headers["Client-Timezone"] = getTimezone();
    options.headers["X-Trace-Id"] = "${DateTime.now().millisecondsSinceEpoch}-${Random().nextInt(100)}";

    var token = await SPUtils.get(CacheConstants.userToken);
    if (token is String && token.isNotEmpty) {
      options.headers["Authorization"] = token;
    }

    super.onRequest(options, handler);
  }

  String getTimezone() {
    var offset = DateTime.now().timeZoneOffset.inMilliseconds;
    var now = DateTime.now().millisecondsSinceEpoch;
    var utc = now - offset;
    return "${(utc - now) / (1000 * 3600)}";
  }
}
